//
//  HEOtherBindPhoneViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/15.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOtherBindPhoneViewController.h"
#import "HELoginRequest.h"

@interface HEOtherBindPhoneViewController ()

@property (strong, nonatomic) QMUITextField *usernameTF;
@property (strong, nonatomic) QMUITextField *codeTF;
@property(nonatomic, strong) QMUIFillButton *bindingBtn;
@property(nonatomic, strong) QMUIFillButton *codeBtn;

@end

@implementation HEOtherBindPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (_intoType == HEOtherBindPhoneTypeAuth) {
        self.title = @"绑定手机号";
        [self setupNav];

    }else {
        self.title = @"更换手机号";
    }
    
    [self initUI];
    
    [_usernameTF becomeFirstResponder];
}

- (void)setupNav {
    [self zx_setLeftBtnWithImg:IMAGE_NAMED(@"back_black") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
}

- (void)initUI {
    
    // 手机号
    UILabel *realLb = [UILabel new];
    realLb.text = @"手机号";
    realLb.font = DYBlodFont(16);
    realLb.textColor = CNavLightBlackColor;
    realLb.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:realLb];
    
    // 验证码
    UILabel *codeLb = [UILabel new];
    codeLb.text = @"验证码";
    codeLb.font = DYBlodFont(16);
    codeLb.textColor = CNavLightBlackColor;
    codeLb.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:codeLb];
    
    // 账户
    _usernameTF = [[QMUITextField alloc] init];
    self.usernameTF.backgroundColor = [UIColor qmui_colorWithHexString:@"F1F3F8"];
    self.usernameTF.maximumTextLength = 11;
    self.usernameTF.placeholder = @"请输入手机号";
    self.usernameTF.font = DYFont(16);
    self.usernameTF.layer.cornerRadius = 4;
    self.usernameTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    self.usernameTF.clearButtonMode = UITextFieldViewModeAlways;
    self.usernameTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview: _usernameTF];

    // 验证码
    _codeTF = [[QMUITextField alloc] init];
    self.codeTF.backgroundColor = [UIColor qmui_colorWithHexString:@"F1F3F8"];
    self.codeTF.maximumTextLength = 6;
    self.codeTF.placeholder = @"请输入验证码";
    self.codeTF.font = DYFont(16);
    self.codeTF.layer.cornerRadius = 4;
    self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    self.codeTF.clearButtonMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.codeTF];
    
    // 发送验证码按钮
    _codeBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    self.codeBtn.titleLabel.font = UIFontMake(14);
    [self.codeBtn setBackgroundColor:CNavBgColor];
    [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.view addSubview:self.codeBtn];
    [_codeBtn addTarget:self action:@selector(sendSMS) forControlEvents:UIControlEventTouchUpInside];
    
    // 登录按钮
    _bindingBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    self.bindingBtn.titleLabel.font = UIFontMake(15);
    [self.bindingBtn setBackgroundColor:CNavBgColor];
    if (_intoType == HEOtherBindPhoneTypeAuth) {
        [self.bindingBtn setTitle:@"绑定" forState:UIControlStateNormal];
    }else {
        [self.bindingBtn setTitle:@"更换手机号" forState:UIControlStateNormal];
    }
    
    [self.view addSubview:self.bindingBtn];
    [self.bindingBtn addTarget:self action:@selector(bindingClick) forControlEvents:UIControlEventTouchUpInside];
  
    [realLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_usernameTF);
        make.left.equalTo(self.view).offset(10);
        make.width.offset([realLb.text widthForFont:realLb.font] + 30);
    }];
    
    [_usernameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).mas_offset(ZXNavBarHeight + 15);
        make.left.equalTo(realLb.mas_right);
        make.right.equalTo(self.view).mas_offset(-15);
        make.height.mas_offset(40);
    }];
    
    [codeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_codeTF);
        make.left.equalTo(self.view).offset(10);
        make.width.offset([realLb.text widthForFont:realLb.font] + 30);
    }];
    
    [_codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_usernameTF.mas_bottom).mas_offset(15);
        make.left.equalTo(codeLb.mas_right);
        make.right.equalTo(_codeBtn.mas_left).mas_offset(-15);
        make.height.mas_offset(40);
    }];
    
    [_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_codeTF);
        make.height.mas_offset(34);
        make.width.mas_offset(100);
        make.right.equalTo(self.view.mas_right).mas_offset(-15);
    }];
      
    [_bindingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_codeTF.mas_bottom).mas_offset(30);
        make.left.equalTo(self.view).mas_offset(30);
        make.right.equalTo(self.view.mas_right).mas_offset(-30);
        make.height.mas_offset(40);
    }];
}

- (void)sendSMS {
    NSString *phone = _usernameTF.text;
    
    // 判断手机号格式是否正确
    if (![WOValidate valiMobile:phone]) {
         [Dialog toast:@"请输入正确的手机号码" delay:2];
        return;
    }
    
    if (_intoType == HEOtherBindPhoneTypeChangePhone) {
        if ([[UserManager sharedUserManager].curUserInfo.username isEqualToString:_usernameTF.text]) {
            [Dialog toastBottom:@"该账户已存在"];
            return;
        }
    }
    
    // 记录手机号
    [kUserDefaults setObject:phone forKey:KUserName];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:phone forKey:@"phone"];
    if (_intoType == HEOtherBindPhoneTypeAuth) {
        [params setObject:@"sms_auth" forKey:@"smsType"];
    }else {
        [params setObject:@"sms_change_username" forKey:@"smsType"];
    }
    [params setObject:[NSNumber numberWithInt:1] forKey:@"source"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KSendSMSUrl parameters:params token:nil success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [Dialog toast:@"短信发送成功" delay:2];
            [self openCountdown];
        }
    } failure:^(NSError * _Nonnull error) {

    }];
}

- (void)bindingClick {
    
    if ([DYTools isBlankString:_codeTF.text]) {
        [Dialog toastBottom:@"请输入验证码"];
        return;
    }
    
    if (_intoType == HEOtherBindPhoneTypeAuth) {
        [self bindingUsername];
    }else {
        [self changeUsername];
    }
}

- (void)bindingUsername {
    HELoginRequest *loginReq = [HELoginRequest new];
    loginReq.type = 2;
    loginReq.username = _usernameTF.text;
    loginReq.password = [DYTools md5:[NSString stringWithFormat:@"%@%@",self.usernameTF.text, kHash]];
    loginReq.platform = @"iOS";
    loginReq.source = 1;
    loginReq.openId = _openId;
    loginReq.unionId = _unionId;
    loginReq.smsCode = _codeTF.text;
    loginReq.registrationId = [JPUSHService registrationID];
    loginReq.identityType = _identityType;
    loginReq.method = _method;

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KLoginUrl parameters:loginReq token:nil success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.code == 203) { // 已绑定 登录
            UserInfo *data = [UserInfo mj_objectWithKeyValues:response.data];
            
            // 存储用户数据
            [[UserManager sharedUserManager] saveUserInfo:data];
            
            // 存储token
            [[UserManager sharedUserManager] saveToken:response.jwtToken forKey:data.username];
            
            // 连接socket
            [[HESocketManager sharedManager] connect];
         
            MainTabBarController *tabBarViewController = [[MainTabBarController alloc] init];
            self.view.window.rootViewController = tabBarViewController;
            [self.view.window makeKeyAndVisible];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)changeUsername {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:_usernameTF.text forKey:@"phone"];
    [dict setValue:_codeTF.text forKey:@"code"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KchangeUsername parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.code == 101) { // 已绑定 登录
            UserInfo *data = [UserInfo mj_objectWithKeyValues:response.data];
            
            // 存储用户数据
            [[UserManager sharedUserManager] saveUserInfo:data];
            
            // 存储token
            [[UserManager sharedUserManager] saveToken:response.jwtToken forKey:data.username];
              
//            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationUserInfoChange object:nil];
            
            [Dialog toastBottom:@"更换成功"];
            [[UserManager sharedUserManager] reloadMain];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}


// 开启倒计时效果
- (void)openCountdown{

    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{

                //设置按钮的样式
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = YES;
            });

        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{

                //设置按钮显示读秒效果
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%ldS", seconds] forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
